package com.heima.search.listen;

import com.heima.common.constants.message.NewsUpOrDownConstants;
import com.heima.common.exception.CustException;
import com.heima.feigns.ArticleFeign;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.vos.SearchArticleVO;
import com.heima.search.service.ArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
@Slf4j
public class ArticleAddOrRemoveListener {
    //注入ArticleFeign接口
    @Autowired
    ArticleFeign articleFeign;

    //注入搜索service
    @Autowired
    ArticleSearchService articleSearchService;


    /**
     * 监听保存文章消息
     * @param articleId 文章id
     */
    @RabbitListener(queuesToDeclare = @Queue(value = NewsUpOrDownConstants.NEWS_UP_FOR_ES_QUEUE))
    public void saveArticle(String articleId){
        log.info("搜索微服务 接收到添加文章到索引库消息==> {}",articleId);
        ResponseResult<SearchArticleVO> result = articleFeign.findArticle(Long.valueOf(articleId));
        //判断状态码
        if (!result.checkCode()) {
            log.info("远程调用ArticleFeign接口失败了! 文章id : {}",articleId);
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,"远程调用ArticleFeign接口失败!");
        }
        //拿出数据
        SearchArticleVO articleVO = result.getData();
        //判断数据是否为空
        if (articleVO==null) {
            log.info("索引库添加文章失败! 文章id : {}",articleId);
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);
        }

        try {
            articleSearchService.saveArticle(articleVO);
            log.info("成功更新索引信息   add: {}",articleId);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("消息消费确认失败   文章id: {}  原因: {}",articleId,e.getMessage());
        }
    }


    /**
     * 监听删除文章消息
     * @param articleId 文章id
     */
    @RabbitListener(queuesToDeclare = @Queue(value = NewsUpOrDownConstants.NEWS_DOWN_FOR_ES_QUEUE))
    public void deleteArticle(String articleId){
        log.info("搜索微服务 接收到删除文章到索引库消息==> {}",articleId);
        //直接调用删除方法
        try {
            articleSearchService.deleteArticle(articleId);
            log.info("成功更新索引信息   delete: {}",articleId);
        } catch (Exception e) {
            e.printStackTrace();
            log.error("消息消费确认失败   文章id: {}  原因: {}",articleId,e.getMessage());
        }

    }
}